package com.my.study.io;

import java.io.*;

/**
 * @author Carlos
 * @version 1.0
 * @Description 流工具
 * @date 2021/7/3 22:15
 **/
public class StreamUtils {

    /**
     * 将输入流转换成byte[]，即可以把文件暂时读入到byte[]中
     *
     * @param is 字节输入流
     * @return byte[] 存储输入流内容
     * @throws IOException
     */
    public static byte[] streamToByteArray(InputStream is) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        BufferedInputStream bis = new BufferedInputStream(is);
        int len = 0;
        while ((len = bis.read(buf)) != -1) {
            bos.write(buf, 0, len);
        }
        byte[] array = bos.toByteArray();
        bis.close();
        bos.close();
        return array;
    }

    public static String streamToString(InputStream is) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\r\n");
        }
        return sb.toString();
    }

}
